import {
  tool,
  api,
  mta,
} from './../../../utils/quoteConfig.js'
const app = getApp()

const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器

Page({

  /**
   * 页面的初始数据
   */
  data: {
    aa: [0, 0, 0, 0, 0],
    isindex: 0,
    current: 0,
    current3: 0,
    isBrang: app.globalData.isBrang,
    oneguide: true, //引导页
    twoguide: false,
    threeguide: false,
    main: true,
    img: null,
    eword: null,
    cword: null,
    molecule: true,
    err: false, //错误的单词页面
    num: 0, //点击正确单词加1
    cpArr: ['', '', ''],
    index: 0,
    imgUrl: null,
    WordList: '',
    _WordList: '',
    data: null,
    form: true, //进入测验需要切换状态
    form1: true,
    form2: false,
    bac: false,
    bar: 0,
    studybar: 0,
    mo: 1,
    mom: true, //
    number: '',
    glide: false, //进入测验需要切换状态
    id: '',
    length: 0, //位移距离
    isShowEndTip: false, //弹窗
    evaluating: false,   
    PageIndex: 0, //
   
    studyArr: [], //学习单词长度数组
    hash: [],
    str: '', //課程名稱
    moleculeProgress: true, //
    isListenstar: false,
    isListenEnd: true,
    studyspeed: ['', ], //侧滑增加的进度条
    selectspeed: [], //答题进度条
    moleculesss: 0,
    yesanswer: false,
    glide_left: true, //左滑箭头
    test: false, //测试题
    swiper: {
      indicatorDots: false,
      circular: true,
      autoplay: false,
      interval: 5000,
      duration: 1000,
      current: 0,
      list: '',
    }
  },
  isClick: false,
  stopMusic: true,
  beforeindex: 0,
  onLoad: function(options) {
    mta.Page.init(); //初始化腾讯埋点
    console.log(options.CourseId)
    let that = this
    that.endTip = this.selectComponent("#endTip"); //彈窗組件
    wx.getStorage({
      key: 'twoguide',
      success: function(res) {
        console.log(res, '212121')
        if (res.data != null) {
          that.setData({
            oneguide: false,
            twoguide: false,
            threeguide: false,
          })
        } else if (res.errMsg != null) {
          that.setData({
            oneguide: false,
            twoguide: false,
            threeguide: false,
          })
        }
      },
    })
    that.setData({
      imgUrl: app.globalData.imgUrl,
      str: options.str //課程名稱
    })
    this.getTaskThreeData()

    setTimeout(function() {
      that.setData({
        glide: true
      })
    }, 1000);

    innerAudioContext.stop();

    var valHandlers = setTimeout(function() {
      let word = that.data.swiper.list[that.data.swiper.current].Word
      that.data.studyArr.push(word)
      that.Sbaudio(word) //调用扇贝第单词发音接口
      //  tool.Sbaudio(word)
    }, 1500)

  },
  onReady: function() {
    var that = this
  },
  onShow: function() {
      console.log('页面切换qaq')
  },
  onHide: function() {
    innerAudioContext.offEnded()
  },
  onUnload: function() {
    var that = this
    console.log('清理定时器')
    clearTimeout(that.data.valHandlers)
    innerAudioContext.offEnded()
  },
  //调用扇贝第单词发音接口
  Sbaudio(word, mold) {
    let that = this
 
    console.log(mold, '6546431')
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/',
      data: {
        word: word
      },
      success: function(res) {
        console.log(res, '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
        innerAudioContext.src = res.data.data.audio_addresses.uk[0]
        innerAudioContext.play()
        innerAudioContext.onEnded((res) => {
          console.log('监听音频自然播放至结束的事件1')         
          that.stopMusic = true
          if (mold == 1) {
            that.setData({
              isListenEnd: true,
              isListenstar: false
            })
          }
        })
      }
    })
  },
   aaaa(){
        wx.request({
          url: 'https://api.shanbay.com/bdc/example/',
          data:{
            vocabulary_id:1684
          },
          success:function(res){
            console.log(res,'_________________________________________________')
          }
        })
   },
  //点击知道了
  got() {
    let that = this
    that.setData({
      oneguide: false,
      twoguide: true,
      molecule: false
    })
    wx.setStorage({
      key: 'twoguide',
      data: 'twoguide',
    })
  },
  got_two() {
    let that = this
    that.setData({
      twoguide: false,
      molecule: true
    })
    wx.setStorage({
      key: 'oneguide',
      data: 'oneguide',
    })
  },
  got_three() {
    let that = this
    that.setData({
      threeguide: false,
      oneguide: false,
      twoguide: false,
      molecule: true
    })
    // wx.removeStorage('oneguide', 'oneguide')
    wx.removeStorage({
      key: 'oneguide',
      success: function(res) {
        console.log(res, '*****')
      },
    })
  },

  
  //获取看图学单词的数据
   getTaskThreeData: function() {
 
    var list = 'swiper.list'
    var dataDic = {
      //  ModuleId :22
      ModuleId: app.globalData.moduleId
    };
    var that = this
    api.methodBasicEnglish_Img({
      dataDic: dataDic,
      success: function(res) {
        console.log(res, '列表数据')
        var Data = res.data.data.WordImgList
        Data.forEach(item => {
          item.imageUrl = app.globalData.imgUrl + item.ImgUrl
          item.WAudioAddress = app.globalData.audioUrl + item.WAudioAddress
          item.SAudioAddress = app.globalData.audioUrl + item.SAudioAddress
        })
        that.setData({
          [list]: Data,
          number: Data.length,
        })
        setTimeout(() => {
          that.setData({
            studybar: 1 / that.data.number * 100,
            bar: 1 / that.data.number * 100
          })
          console.log(that.data.studybar)
        }, 200)
      },
      fail: function(err) {
        wx.showModal({
          title: '温馨提示',
          content: err.errMsg,
        })
      }
    })
  },

  //测评接口
  evaluat(e) {
    let that = this
    //    return
    var dataDic = {
      ModuleId: app.globalData.moduleId,
      PageIndex: that.data.PageIndex,
      // PageSize: 3,
      //   PageSize:that.data._WordList.length,
    };
    api.methodBasicEnglish_WordDetection({
      dataDic,
      success: function(res) {
        console.log(res, '******************')

        that.setData({
          _WordList: res.data.data.Detection,
          form: false,
          evaluating: true,
          glide_left: false, //隐藏箭头
        })
      }
    })

  },
  //选择答案
  selectAnswer(e) {
    let that = this
    let str = that.data.str
    var num = that.data.num
    var PageIndex = that.data.PageIndex
    var index = that.data.index //
    var cpArr = that.data.cpArr
    var _index = e.currentTarget.dataset.index
    var music = e.currentTarget.dataset.music
    var current = 'swiper.current'
    var statu = e.currentTarget.dataset.statu
    var eword = e.currentTarget.dataset.eword //英文错误
    var cword = e.currentTarget.dataset.cword //中文错误
    var img = e.currentTarget.dataset.img
    var length = that.data.length //位移长度 
    var wordArr = that.data._WordList[index].WordList

    //  console.log(wordArr, '369')
    cpArr.splice(_index, 1, 1)
    that.setData({
      cpArr: cpArr,      
    })
    console.log(that.isClick,'307')
    if(that.isClick){
    
      return
    }
    var length2 = length + (600 / that.data.swiper.list.length)
    // console.log(length2, '255')  var bar = (hash.length / that.data.number) * 100
    if (statu == true) {
      console.log('答案正确', that.data.bar, that.data.hash.length, that.data.cuurrent3, eword, that.data.selectspeed)
      var newselectspeed = that.data.selectspeed //
      newselectspeed.push('')
      console.log(newselectspeed, newselectspeed.length, '475', that.data.swiper.list.length)
      
      if (newselectspeed.length <= that.data.swiper.list.length) {

        that.setData({
          selectspeed: newselectspeed,
          yesanswer: true,
        })
      } else {
        console.log('结束')
        //  return
      }
      that.Sbaudio(eword)
      app.aldstat.sendEvent('回答正確', {
        'wordtest': eword,
        'index': 0,
        'course': str
      });
      mta.Event.stat('answer_yes', {
        'wordtest': eword,
        'index': 0,
        'course': str
      })
      that.isClick = true
  
      setTimeout(() => {
        var index = that.data.index
        var newindex = index + 1
        cpArr.splice(_index, 1, 0)
        that.isClick = false
        that.setData({
          index: newindex,
          cpArr: cpArr,
          _WordList: that.data._WordList,
        })
        console.log(newindex, that.data._WordList[index].WordList.length, '346')
        if (newindex == that.data._WordList[index].WordList.length) {
          console.log('----')

          console.log(that.data.hash.length, that.data.swiper.list.length, '405')
          if (that.data.hash.length == that.data.swiper.list.length) {
            console.log('关卡完毕进入下一节')
            //  return
            that.setData({
              glide: false,
              glide_left: false,
              moleculeProgress: false,
              mom: false,
              evaluating: false,
              form: false,
              bac: true,
            })
          } else {
            console.log('正常进入下一组单词学习', that.data.hash, that.data.studyspeed)
            that.data.studyspeed.push('')
            var aa = 'aa[' + that.data.PageIndex + ']'
            console.log(aa,'367')
            var word = that.data.swiper.list[that.data.current].Word
           // var newPageIndex = that.data.PageIndex + 1
          //  console.log(aa, newPageIndex, '0000')
            that.Sbaudio(word)
            // that.evaluat()
            //    that.base = false
            that.isClick=false,
            that.setData({
           //   PageIndex: newPageIndex,
              evaluating: false,
              form: true,
              mo: num,
              index: 0,
        
              glide: true,
              glide_left: true,
              [aa]: 1,
              studyspeed: that.data.studyspeed
            })
            console.log(that.data.studyspeed, that.data.PageIndex,that.data.aa,'569')
            setTimeout(() => {
              that.setData({
                bar: that.data.mo / that.data.number * 100,
              })

            }, 200)
          }
        }

      }, 2000)
    } else if (statu == false) {
      app.aldstat.sendEvent('回答錯誤', {
        'wordtest': eword,
        'index': 1,
        'course': str
      });
      mta.Event.stat('answer_no', {
        'wordtest': eword,
        'index': 1,
        'course': str
      })
      innerAudioContext.src = '/src/record/false.mp3'
      innerAudioContext.play();
      console.log('答案错误')
      console.log(that.data.swiper)
      that.setData({
        cword: cword,
        eword: eword,
        img: img,
        glide_left: false,
        form: false,
        evaluating: false,
        err: true //切换错误的单词
      })
      //   return
      setTimeout(() => {
        cpArr.splice(_index, 1, 0)
        console.log('返回错误的试题')
        that.setData({
          cpArr: cpArr,
          form: false,
          evaluating: true,
          glide_left: false,
          err: false //切换错误的单词
        })
      }, 2000)
    }
  },


  //播放
  audio(e) {
    let that = this
    var str = that.data.str
    that.setData({
      isListenEnd: false,
      isListenstar: true
    })
    innerAudioContext.stop();
    //console.log(e.target.dataset.music)
    var word = e.target.dataset.music
    app.aldstat.sendEvent('点击播放单词音频', {
      'studyword': word,
      'index': 0,
      'course': str
    });
    mta.Event.stat('click_word', {
      'studyword': word,
      'index': 0,
      'course': str
    })
    that.Sbaudio(word, 1)


  },
  //播放句子
  audio_sen(e) {
    let that = this
    var str = that.data.str
    innerAudioContext.stop();
    var music = e.target.dataset.music
    innerAudioContext.src = music
    innerAudioContext.play()
    that.setData({
      isListenEnd: false,
      isListenstar: true
    })
    innerAudioContext.onEnded(() => {
      console.log('监听点击按钮音频自然播放至结束的事件2')
      //   that.stopMusic = truennerAudioContext.offEnded(function callback)
      that.setData({
        isListenEnd: true,
        isListenstar: false
      })
    })
    app.aldstat.sendEvent('点击播放句子音频', {
      'studysentence': music,
      'index': 1,
      'course': str
    });
    mta.Event.stat('click_sentence', {
      'studysentence': music,
      'index': 1,
      'course': str
    })

  },
  //进入轮播下一张
  go_left() {
    let that = this
    var current = 'swiper.current'
    console.log(current)
    console.log(that.data.current, '++++')
    console.log(that.data._WordList.length)
    if (that.data.current == that.data.swiper.list.length - 1) {
      console.log('最后一张进入最后一组测验题')
      that.evaluat()
      //  return

    } else {
      console.log('继续下一张')

      var clickcurrent = that.data.current + 1
      console.log(clickcurrent)
      that.setData({
        current: clickcurrent
      })
    }
  },
  //详情
  go_next() {

    let that = this
    var str = that.data.str
    console.log('______________更新当前页面数据')
    that.setData({
      form1: false,
      glide: false,
      glide_left: true
    })

    innerAudioContext.stop();
    var music = that.data.swiper.list[that.data.current].SAudioAddress
    app.aldstat.sendEvent('點擊向下箭頭播放句子音频', {
      'studysentence': music,
      'index': 2,
      'course': str
    });
    mta.Event.stat('click_crrow', {
      'studysentence': music,
      'index': 2,
      'course': str
    })
    innerAudioContext.src = music
    innerAudioContext.play()
    innerAudioContext.autoplay = true
    innerAudioContext.onEnded(() => {
      console.log('监听音频自然播放至结束的事件3')
      that.stopMusic = true
      // that.setData({
      //   isListenEnd: true,
      //   isListenstar: false
      // })
    })


  },
  //侧滑
  change: function(e) {
    console.log(e, '轮播')
   
    // console.trace()
    let that = this
   //  debugger
    that.stopMusic = true

    var studyspeed = that.data.studyspeed
    
    var current2 = e.detail.current //当前索引//1
    console.log(that.data.studyspeed, '235')
    that.setData({
      form1: true,
      //isClick: true,
    })
    console.log(that.data.studyspeed, '238')
    console.log(current2, that.beforeindex, '254')
    that.beforeindex = e.detail.current
    that.setData({
      current: current2, //存储页面索引 
     
    })
    if (current2 <= 3) {
      that.setData({
        PageIndex: 0
      })
    } else if (current2 > 3 && current2 <= 6) {
      that.setData({
        PageIndex: 1
      })
    } else if (current2 > 6 && current2 <= 9) {
      that.setData({
        PageIndex: 2
      })
    } else if (current2 > 9 && current2 <= 12) {
      that.setData({
        PageIndex: 3
      })
    } else if (current2 > 12 && current2 <= 15) {
      that.setData({
        PageIndex: 4
      })
    } else if (current2 > 15 && current2 <= 18) {
      that.setData({
        PageIndex: 5
      })
    } else {
      that.setData({
        PageIndex: 6
      })
    }
    console.log(that.data.current)
    if (current2 == 0) {
      
    }

    console.log(current2, that.data.current3, '*0*0*0**0*0*0*0**')
    innerAudioContext.stop();
    var current = 'swiper.current'
    var num = that.data.num //单词学习数量
    var studyArr = that.data.studyArr
    var hash = that.data.hash
    var length = that.data.length
    var isindex = that.data.isindex
    if (current2 == that.data.swiper.list.length - 1) {
      that.isClick = false

    }
    if (current2 % 3 != 0) {
      setTimeout(function() {
        that.setData({
          glide: true
        })
      }, 1000);
    }
    let word = that.data.swiper.list[current2].Word
    console.log(word, '196', that.data.current)
    studyArr.push(word)
    for (var i = 0; i < studyArr.length; i++) {
      if (hash.indexOf(studyArr[i]) == -1) {
        hash.push(studyArr[i]) //学习单词数组去重               
      }
    }
    console.log(that.data.hash, current2, '____________________')
    for (var i = 0; i < that.data.hash.length; i++) {
      if (that.data.hash[i] == "") {
        that.data.hash.splice(i, 1);
        i = i - 1;
      }
    }
    var bar = (hash.length / that.data.number) * 100
    var length2 = length + (600 / that.data.swiper.list.length)
    if (current2 % 3 == 0) {

      if (that.data.current3 >= current2) {
        console.log(that.data.swiper.list[e.detail.current].Word)
        that.Sbaudio(word) //调用扇贝第单词发音接口

        console.log('243')
        that.setData({
          hash: that.data.hash,
          mo: hash.length, //244

        })
      } else {
        that.setData({
          glide: false,
          //   num:num2,
          num: hash.length,
          mom: true,
          length: length2,
        })
        if (that.data.aa[that.data.PageIndex] == 0) {
          that.setData({
            bar: (hash.length - 1) / that.data.number * 100,
            mo: hash.length - 1, //244

          })
        } else {
          that.setData({
            bar: (hash.length) / that.data.number * 100,
            mo: hash.length, //244
          })
        }
      }


    } else if (current2 % 3 != 0) {

      console.log(bar, '359')
      console.log(hash, '368')
      for (var i = 0; i < hash.length; i++) {
        if (hash[i] == "") {
          hash.splice(i, 1);
          i = i - 1;
        }
      }
      console.log(hash, '375')
      that.Sbaudio(word) //调用扇贝第单词发音接口
      that.setData({
        current3: current2,
        glide: false,
        num: hash.length,
        mo: hash.length,
        studyspeed: hash,
        mom: true,
        bar: bar,
        length: length2,
      })
      console.log(current2, '300', that.data.studyspeed)
    }

    // console.log(current2, '108', that.data.swiper.list.length - 1, that.data.current3)
    console.log(that.data.aa[that.data.PageIndex], '381',that.data.PageIndex)
    if (that.data.aa[that.data.PageIndex] == 0) {
     
      if (that.data.current3 <= e.detail.current) {
        console.log('290')


        if (e.detail.current != 0 && e.detail.current % 3 == 0) {
          console.log('291')
          studyspeed.splice(0, 1)
          that.setData({
            studyspeed: studyspeed
          })
          console.log(studyspeed)
          innerAudioContext.stop();
          that.setData({
            glide: false,
          })
          console.log('进入测验入口')
          that.evaluat() //调用测评入口.
          wx.getStorage({
            key: 'oneguide',
            success: function(res) {
              console.log(res.data, '61')
              console.log(that.data.threeguide)
              if (res.data != null) {
                that.setData({
                  threeguide: true,
                  molecule: false
                })
              } else if (res.errMsg != null) {
                that.setData({
                  threeguide: false
                })
              }
            },
          })
          that.setData({
            form: false,
            glide: false,
            glide_left: false,
            evaluating: true, //评测试题
            //  threeguide: true,
          })
          // return
        }
      } else {
        console.log('')
      }
    } else {
      console.log('测过')
      that.setData({
        glide_left: true,
      })
      var danci = that.data.swiper.list[that.data.current].Word
      that.Sbaudio(danci)
    }
  },
  //触摸滑动计算
  endtouchstart(e) {
    console.log(e, '106')
    var self = this
    self.setData({
      clientY: e.changedTouches[0].clientY,
      clientX: e.changedTouches[0].clientX
    })
  },
  //滑动结束位置
  touchEnd(e) {
    var that = this
    var index = that.data.index
    var str = that.data.str

    var endy = e.changedTouches[0].clientY
    var endx = e.changedTouches[0].clientX
    //console.log(that.data.clientY, '117', endy)
    //console.log(that.data.clientX - endx)
    //console.log(that.data.clientY - endy)
    console.log(that.beforeindex, '845')
    if (that.beforeindex == that.data.swiper.list.length - 1) {
      if (that.data.clientX - endx > 50) {
        if (that.data.current >= 12 && that.data.current < 15) {
          that.setData({
            PageIndex: 4
          })
          console.log(that.data.PageIndex, '687')
        } else if (that.data.current >= 15 && that.data.current < 18) {
          that.setData({
            PageIndex: 5
          })
          console.log(that.data.PageIndex, '743')
        }

        that.evaluat()

      }
      console.log('最后一张')


    } else {
      console.log('不是')
    }
    if (that.data.clientY - endy > 80) {
      console.log('______________更新当前页面数据')
      that.setData({
        form1: false,
        glide: false,
        glide_left: true,
      })
      // console.log(that.data.swiper.list[that.data.current].SAudioAddress)
      innerAudioContext.stop();

      var music = that.data.swiper.list[that.data.current].SAudioAddress
      app.aldstat.sendEvent('向下滑動播放句子音频', {
        'studysentence': music,
        'index': 3,
        'course': str
      });
      mta.Event.stat("slide_down", {
        'studysentence': music,
        'index': 3,
        'course': str
      });
      innerAudioContext.src = music
      if (that.stopMusic) {
        innerAudioContext.play()
        innerAudioContext.onEnded(() => {
          console.log('监听音频自然播放至结束的事件4')

          that.stopMusic = false
        })
      }
    }
  },
  //进入游戏环节
  gotoGame: function() {
    var that = this
    that.unlockLevels(1)
  },
  //解锁接口进入下一节
  unlockLevels: function(type) {
    var dataDic = {
      SubtitleId: 2,
      ModuleId: app.globalData.moduleId,
      OpenId: app.globalData.openId
    };
    var that = this
    api.methodBasicEnglish_Unlock({
      dataDic: dataDic,
      success: function(res) {
        console.log('解锁成功', res)
        if (type == 1) {
          that.getGameStatus()
        } else if (type == 2) {
          if(app.globalData.addId == 0){
            app.globalData.addId = 1
            
           wx.reLaunch({
             url: '../../../pages/indexPackage/courseList/courseList?addId='+ 1,
            //  ../../../pages/indexPackage/courseList/courseList
           })
         }else{
           console.log('走缓存处理')
           wx.getStorage({
             key: 'removes',
             success: (res) => {
               console.log(res.data)
               if(res.data){
                 console.log('426')
                 wx.reLaunch({
                   url: '../../../pages/indexPackage/courseList/courseList?addId=' + 2,
                 })
               }
             },
         
           })
         }
        }
      },
      fail: function(err) {
        console.log('解锁失败', err)
      }
    })
  },
  //获取游戏状态
  getGameStatus: function() {

    var that = this
    var dataDic = {
      ModuleId: app.globalData.moduleId,
    };
    api.methodBasicEnglish_GetGameStatus({
      dataDic: dataDic,
      success: function(res) {
        // console.log('数据请求成功', res)
        app.globalData.gameStatus = res.data.data
        //  console.log(app.globalData.gameStatus,'801')
        //  console.log(res.data.data, '803')

          if (res.data.data.GameThree == true) {

          wx.reLaunch({
              url: '/pages/gamePackage/pages/gameFunnel/gameFunnel',
          })
          return
        } else if (res.data.data.GameOne == true) {
          wx.reLaunch({
              url: '/pages/gamePackage/pages/gamePicmate/gamePicmate',
          })
          return
        } else if (res.data.data.GameTwo == true) {
          wx.reLaunch({
              url: '/pages/gamePackage/pages/gameWordspell/gameWordspell',
          })
          return
        }
      },
      fail: function(err) {
        console.log('数据请求失败', err)
      }
    })
  },

  //休息一会
  over() {
    let that = this
    that.unlockLevels(2)
  },

  //结束游戏
  goback() {
    let that = this
    var str = that.data.str
    that.endTip.showPopup();
    app.aldstat.sendEvent('返回按鈕', {
      'index': 5,
      'course': str
    });
    mta.Event.stat("go_courselist", {
      'index': 5,
      'course': str
    });
  },
  //确定
  confirm() {
    let that = this
    // that.statistics()
    tool.statistics(app.globalData.openId, app.globalData.moduleId, 1, 1, 1)
    wx.redirectTo({
      url: '../../../pages/indexPackage/courseList/courseList',
    })
  },
  //取消
  cancal() {
    let that = this
    that.endTip.hidePopup();
  },
  onShareAppMessage: function() {
      return {
          path: 'pages/indexPackage/index/index',
          success: function (res) {
              console.log('转发成功', res);
          },
          fail: function (err) {
              console.log('转发失败', err)
          }
      }
  }
})